/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package encaps.security;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.utils.DatabaseUtil;
import javax.sql.DataSource;
import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 *
 * @author fon_Valter
 */
public class RoleManager 
{
    private DataSource _dataSource;
    private PreparedStatement _ps;
    public RoleManager() throws NamingException 
    {
        _dataSource = DatabaseUtil.getDataSource();
    }
    public Role loadRole(String name) throws SQLException, DataAccessException
    {
        Connection conn = null;
        try {
            conn = _dataSource.getConnection();
            _ps = conn.prepareStatement("SELECT name FROM role WHERE name=?");
            _ps.setString(1, name);
            ResultSet rs = _ps.executeQuery();
            if(!rs.next())
            {
                throw new DataAccessException("Role not found");
            }
            _ps = conn.prepareStatement("SELECT grant_name FROM role_grant WHERE role_name=?");
            _ps.setString(1, name);
            rs = _ps.executeQuery();
            Role r = new Role("name");
            while(rs.next())
            {
                r.addGrant(new Grant(rs.getString("grant_name")));
            }
            return r;
        } 
        /*catch(SQLException ex) 
        {
            
        } */
        finally 
        {
            DatabaseUtil.closeConnection(conn, _ps);
        }
    }
    public void updateRole(String oldname, Role r) throws SQLException, DataAccessException
    {
        Connection conn = null;
        try {
            conn = _dataSource.getConnection();
            _ps = conn.prepareStatement("SELECT name FROM role WHERE name=?");
            _ps.setString(1, oldname);
            ResultSet rs = _ps.executeQuery();
            if(!rs.next())
            {
                throw new DataAccessException("Role not found");
            }
            _ps = conn.prepareStatement("DELETE FROM role_grant WHERE role_name=?");
            _ps.setString(1, oldname);
            if (_ps.executeUpdate() != 1) {
                throw new SQLException("Delete error");
            }
            if(!oldname.equals(r.getRoleName()))
            {
                _ps = conn.prepareStatement("UPDATE role SET name=? WHERE name=?");
                _ps.setString(1, oldname);
                _ps.setString(1, r.getRoleName());
                if (_ps.executeUpdate() != 1) {
                    throw new SQLException("Update error");
                }
            }
            _ps = conn.prepareStatement("INSERT INTO role_grant(role_name,grant_name) VALUES(?,?) ");
            String[] grants = r.getGrants().split(";");
            for(int i = 0; i<grants.length;i++)
            {
                _ps.setString(1, r.getRoleName());
                _ps.setString(2, grants[i]);
                if (_ps.executeUpdate() != 1) 
                {
                    throw new SQLException("Insert error");
                }
            }
        } 
        /*catch(SQLException ex) 
        {
            
        } */
        finally 
        {
            DatabaseUtil.closeConnection(conn, _ps);
        }
    }
    public void storeRole(Role r) throws SQLException, DataAccessException
    {
        Connection conn = null;
        try {
            if(isRoleExist(r.getRoleName()))
            {
                throw new DataAccessException("Role are already exist");
            }
            conn = _dataSource.getConnection();
            _ps = conn.prepareStatement("ISERT INTO role(name) VALUES(?)");
            _ps.setString(1, r.getRoleName());
            if (_ps.executeUpdate() != 1) {
                throw new SQLException("Insert error");
            }
            
            _ps = conn.prepareStatement("INSERT INTO role_grant(role_name,grant_name) VALUES(?,?) ");
            String[] grants = r.getGrants().split(";");
            for(int i = 0; i<grants.length;i++)
            {
                _ps.setString(1, r.getRoleName());
                _ps.setString(2, grants[i]);
                if (_ps.executeUpdate() != 1) 
                {
                    throw new SQLException("Insert error");
                }
            }
        } 
        /*catch(SQLException ex) 
        {
            
        } */
        finally 
        {
            DatabaseUtil.closeConnection(conn, _ps);
        }
    }
    public boolean isRoleExist(String name) throws SQLException
    {
        Connection conn = null;
        try {
            conn = _dataSource.getConnection();
            _ps = conn.prepareStatement("SELECT name FROM role WHERE name=?");
            _ps.setString(1, name);
            ResultSet rs = _ps.executeQuery();
            if(!rs.next())
                return false;
            else return true;
        } 
        /*catch(SQLException ex) 
        {
            
        } */
        finally 
        {
            DatabaseUtil.closeConnection(conn, _ps);
        }
    }
}
